package com.sangmo.fts.clazz.service;

import com.sangmo.boot.framework.data.filter.NativeQueryBuilder;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.boot.framework.plugin.dataview.spi.jpa.NativeQueryBuilderFactory;
import com.sangmo.fts.clazz.model.Clazz;
import com.sangmo.fts.clazz.repo.ClazzRepo;
import com.sangmo.fts.external.response.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

@Service
@Transactional
public class ClazzEntityService extends BaseViewService<Clazz> {

    @Autowired
    private ClazzRepo clazzRepo;

    @Override
    protected IDataViewRepo<Clazz> getRepo() {
        return clazzRepo;
    }

    protected Clazz findByExClazzId(String exClazzId) {
        return clazzRepo.findByExClazzId(exClazzId);
    }

    protected Collection<Clazz> findByUserId(Long userId) {
        return clazzRepo.findByUserId(userId);
    }

    protected Collection<Clazz> findByExaminationId(Long examinationId) {
        return clazzRepo.findByExaminationId(examinationId);
    }

    protected PageResult<Clazz> searchByUserId(Long userId, PageSearch ps) {
        NativeQueryBuilder builder = NativeQueryBuilderFactory.create()
                .selectForm("SELECT a.* FROM clazz a ")
                .where(" EXISTS(SELECT uc.clazz_id from user_clazz uc where uc.user_id = :userId and uc.clazz_id = a.id)")
                .where(ps)
                .putVariable("userId", userId)
                .transform(Clazz.class);
        return builder.buildPage();
    }
}
